<template>
  <common-layout>
    <div class="top">
      <div class="header">
        <img alt="logo" class="logo" src="@/pages/list/menu/images/logo.png"/>
        <span class="title">{{ systemName }}</span>
      </div>
      <div class="desc">乐购后台管理系统</div>
    </div>
    <div class="login">
      <a-form @submit="onSubmit" :form="form">
        <a-tabs size="large" :tabBarStyle="{textAlign: 'center'}" style="padding: 0 2px;">
          <a-tab-pane tab="账户密码登录" key="1">
            <a-alert type="error" :closable="true" v-show="error" :message="error" showIcon
                     style="margin-bottom: 24px;"/>
            <a-form-item>
              <a-input
                  autocomplete="autocomplete"
                  size="large"
                  v-decorator="['name', {rules: [{ required: true, message: '请输入账户名', whitespace: true}]}]"
              >
                <a-icon slot="prefix" type="user"/>
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-input
                  size="large"
                  autocomplete="autocomplete"
                  type="password"
                  v-decorator="['password', {rules: [{ required: true, message: '请输入密码', whitespace: true}]}]"
              >
                <a-icon slot="prefix" type="lock"/>
              </a-input>
            </a-form-item>
          </a-tab-pane>
        </a-tabs>
        <div>
          <a-checkbox :checked="true">自动登录</a-checkbox>
          <a style="float: right">忘记密码</a>
        </div>
        <a-form-item>
          <a-button :loading="logging" style="width: 100%;margin-top: 24px" size="large" htmlType="submit"
                    type="primary">登录
          </a-button>
        </a-form-item>
        <div>
          <router-link style="float: right" to="/dashboard/workplace">注册账户</router-link>
        </div>
      </a-form>
    </div>
  </common-layout>
</template>

<script>
import CommonLayout from '@/layouts/CommonLayout'
import {login, getRoutesConfig} from '@/services/user'
import {METHOD, request, setAuthorization} from '@/utils/request'
import {loadRoutes} from '@/utils/routerUtil'
import {mapMutations} from 'vuex'

export default {
  name: 'Login',
  components: {CommonLayout},
  data() {
    return {
      logging: false,
      error: '',
      apiBaseUrl: `${window.location.protocol}//${window.location.hostname}:8080`,
      form: this.$form.createForm(this)
    }
  },
  computed: {
    systemName() {
      return this.$store.state.setting.systemName
    }
  },
  methods: {
    ...mapMutations('account', ['setUser', 'setPermissions', 'setRoles']),
    onSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err) => {
        if (!err) {
          this.logging = true
          const name = this.form.getFieldValue('name')
          const password = this.form.getFieldValue('password')
          login(name, password).then(this.afterLogin);
        }
      })
    },
    async afterLogin(res) {
      this.logging = false
      const loginRes = res.data
      if (loginRes.code == 200) {
        try {
          // 调用后端 API 获取用户信息

          const response = await request(
              `${window.location.protocol}//${window.location.hostname}:8080/api/admin/info`,
              METHOD.GET,
              {id: loginRes.data.id}
              , {
                headers: {
                  Authorization: `Bearer ${loginRes.data.token}`
                }
              }
          );

          console.log('userRes', response)

          if (response.data.code == 200) {

            // const users = userRes.data;

            let {user, permissions, roles, token, expireAt} = loginRes.data;

            // 你可以在这里模拟假数据
            if (!user || !permissions || !roles) {
              // 模拟的数据
              user = {
                name: response.data.data.nickname == "" ? "乐购" : response.data.data.nickname,
                avatar: response.data.data.avatar == "http://localhost:8080" || `${window.location.protocol}//${window.location.hostname}:8080` ? `${window.location.protocol}//${window.location.hostname}:8080/api/uploads/default_avatar.png` : response.data.data.avatar,
                address: 'New York',
                position: 'Manager'
              };

              permissions = [
                {id: 'queryForm', operation: ['add', 'edit']}
              ];

              roles = [
                {id: 'admin', operation: ['add', 'edit', 'delete']}
              ];
              expireAt = new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000).toISOString(); // 模拟过期时间
            }
            this.setUser(user);
            this.setPermissions(permissions);
            this.setRoles(roles);

            // 设置 Authorization Token 和过期时间
            setAuthorization({token, id: loginRes.data.id, expireAt: new Date(expireAt)});

            // 获取路由配置
            getRoutesConfig().then(result => {
              const routesConfig = result.data.data;
              loadRoutes(routesConfig);
              this.$router.push('/workplace'); // 跳转到工作台
              this.$message.success(loginRes.msg, 3); // 显示登录成功信息
            });
          }
        } catch (error) {
          console.error(error);
        }
      } else {
        this.error = loginRes.msg;
      }
    }
  }
}
</script>

<style lang="less" scoped>
.common-layout {
  .top {
    text-align: center;

    .header {
      height: 44px;
      line-height: 44px;

      a {
        text-decoration: none;
      }

      .logo {
        width: 150px;
        height: 125px;
        vertical-align: top;
        margin-right: 16px;
      }

      .title {
        font-size: 33px;
        color: @title-color;
        font-family: 'Myriad Pro', 'Helvetica Neue', Arial, Helvetica, sans-serif;
        font-weight: 600;
        position: relative;
        top: 2px;
      }
    }

    .desc {
      font-size: 28px;
      font-family: 黑体;
      color: @text-color-second;
      margin-top: 50px;
      margin-bottom: 10px;
    }
  }

  .login {
    width: 368px;
    margin: 0 auto;
    @media screen and (max-width: 576px) {
      width: 95%;
    }
    @media screen and (max-width: 320px) {
      .captcha-button {
        font-size: 14px;
      }
    }

    .icon {
      font-size: 24px;
      color: @text-color-second;
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: @primary-color;
      }
    }
  }
}
</style>
